package com.atguigu.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.core.listener.ExcelDictDTOListener;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.List;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author zwj
 * @since 2021-10-08
 */
@Slf4j
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 数据字典导出excel
     * @param inputStream
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importData(InputStream inputStream) {
        EasyExcel.read(inputStream, ExcelDictDTO.class,new ExcelDictDTOListener(baseMapper)).sheet().doRead();
        log.info("所有数据解析完毕");
    }

    /**
     * 获取所有dict对象并转换为ExcelDictDTO
     * @return
     */
    @Override
    public List<ExcelDictDTO> listDictData() {
        return baseMapper.excelList();
    }

    /**
     * 列出所有父节点id为指定id的dict并设置hasChild属性
     * @param parentId
     * @return
     */
    @Override
    public List<Dict> listByParentId(Long parentId) {
        List<Dict> list=null;
        try {
            list=(List<Dict>)redisTemplate.opsForValue().get("srb:core:dictList"+parentId);
            if(!list.isEmpty()){
                log.info("从redis中取出父节点Id为{}的List<Dict>",parentId);
                return list;
            }
        } catch (Exception e) {
            log.error("redis服务器出错"+ ExceptionUtils.getStackTrace(e));
        }
        log.info("从数据库中取出父节点Id为{}的List<Dict>",parentId);
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",parentId);
        list=baseMapper.selectList(wrapper);
        list.forEach(dict -> {
            dict.setHasChildren(hasChildren(dict));
        });
        try {
            log.info("将父节点Id为{}的List<Dict>存入redis",parentId);
            redisTemplate.opsForValue().set("srb:core:dictList"+parentId,list);
        } catch (Exception e) {
            log.error("redis服务器出错"+ ExceptionUtils.getStackTrace(e));
        }
        return list;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {

        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict dict = baseMapper.selectOne(wrapper);
        return listByParentId(dict.getId());
    }

    /**
     * 判断该节点是否还有子节点
     * @param dict
     * @return
     */
    private boolean hasChildren(Dict dict) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",dict.getId());
        Integer count = baseMapper.selectCount(wrapper);
        return count>0;
    }

    public String getNameByParentDictCodeAndValue(String dictCode, Integer value) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode).select("id");
        Dict dict = baseMapper.selectOne(wrapper);

        if (dict == null) {
            return null;
        }

        wrapper=new QueryWrapper<>();
        wrapper.eq("parent_id",dict.getId()).eq("value",value).select("name");
        List<Object> objects = baseMapper.selectObjs(wrapper);
        return (String)objects.get(0);
    }
}
